package com.woniuxy.intellihome.controller.admin;


import com.woniuxy.intellihome.entity.*;
import com.woniuxy.intellihome.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/admin/SKU")
public class SkuController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private GoodsSpecDetailService gsdService;
    @Autowired
    private SpecDetailService detailService;

    /**
     * 得到级联框的menu
     *
     */
    @RequestMapping("getSelectMenu")
    public ResponseEntity<List<Category>> getSelectMenu() {
        List<Category> categoryList = categoryService.list();
        List<Category> categoriesAndSPUs = new ArrayList<>();
        for (Category category : categoryList) {
            Category cas = categoryService.getCategoryAndItsSPU(category.getId());
            categoriesAndSPUs.add(cas);
        }
        return new ResponseEntity<>(categoriesAndSPUs);
    }

    //得到一个详细的sku
    @RequestMapping("getskubyskuid")
    public ResponseEntity<Sku> getFullSku(int skuid) {
        Sku sku = skuService.getWithSpuSpecDetailBySKUId(skuid);
        return new ResponseEntity<>(sku);
    }

    //得到隶属spu的sku list
    @RequestMapping("getallskubyspuid")
    public ResponseEntity<List<Sku>> getAllSkuBySpuId(int spuId) {
        List<Sku> skuList = skuService.getAllSkuBelong2Spu(spuId);
        return new ResponseEntity<>(skuList);
    }

    //上下架
    @RequestMapping("upDown")
    public ResponseEntity<Sku> changeStatus(int id){
        Sku sku = skuService.getById(id);
        if("y".equals( sku.getStatus())){
            sku.setStatus("n");
        }else{
            sku.setStatus("y");
        }
        skuService.updateById(sku);
        return new ResponseEntity<>(sku);
    }

    @RequestMapping("add")
    public ResponseEntity<Void> add(@RequestBody Sku sku) {
        sku.setStatus("y");
        skuService.save(sku);
        List<SpecDetail> details = sku.getDetails();
        for (SpecDetail detail : details) {
            GoodsSpecDetail temp = new GoodsSpecDetail();
            temp.setSkuId(sku.getId());
            temp.setGoodsId(sku.getSpu().getId());
            temp.setSpecDetailId(detail.getId());
            SpecDetail fullDetail = detailService.getById(detail.getId());
            temp.setSpecId(fullDetail.getSpecId());
            gsdService.save(temp);
        }
//        System.out.println("新加sku" + sku);
        return  ResponseEntity.SUCCESS;
    }
}

